
#include <stdint.h>
#include <string.h>

#include "tlg.h"
#include "tlg_bmp.h"

static uint8_t* tlg_bmp_write_int32(uint8_t * buffer, int32_t n)
{
	*buffer++ = n & 0xff;
	*buffer++ = (n>>8) & 0xff;
	*buffer++ = (n>>16) & 0xff;
	*buffer++ = (n>>24) & 0xff;
	return buffer;
}

static uint8_t* tlg_bmp_write_int16(uint8_t * buffer, int32_t n)
{
	*buffer++ = n & 0xff;
	*buffer++ = (n>>8) & 0xff;
	return buffer;
}

int tlg_to_bmp_ibuffer(tlg_t* tlg, uint8_t * buffer)
{
	int header_size = 14;
	int dib_header_size = 40;
	int data_size = tlg->width * tlg->height * tlg->colors;
	int file_size = data_size + header_size + dib_header_size;

	*buffer++ = 'B';
	*buffer++ = 'M';
	buffer = tlg_bmp_write_int32(buffer, file_size);
	buffer = tlg_bmp_write_int32(buffer, 0);
	buffer = tlg_bmp_write_int32(buffer, header_size + dib_header_size);

	buffer = tlg_bmp_write_int32(buffer, dib_header_size);
	buffer = tlg_bmp_write_int32(buffer, tlg->width);
	buffer = tlg_bmp_write_int32(buffer, -tlg->height);
	buffer = tlg_bmp_write_int16(buffer, 1);
	buffer = tlg_bmp_write_int16(buffer, tlg->colors*8);

	buffer = tlg_bmp_write_int32(buffer, 0);
	buffer = tlg_bmp_write_int32(buffer, 0);
	buffer = tlg_bmp_write_int32(buffer, 0x0ec4); // XXX
	buffer = tlg_bmp_write_int32(buffer, 0x0ec4); // XXX
	buffer = tlg_bmp_write_int32(buffer, 0);
	buffer = tlg_bmp_write_int32(buffer, 0);

	memcpy(buffer, tlg->buffer, data_size);
	return 0;
}

